package wqh.cfs2000;

import cn.tpson.dti.common.*;
import cn.tpson.dti.core.IDataProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import wqh.domain.AlarmInComming;
import wqh.global.GlobalDevice;
import wqh.pojo.IPConver;
import wqh.service.AlarmInCommingService;
import wqh.websocket.alarm.AlarmSocketHandler;


/**
 * Created by devts on 2016/9/23.
 */
public class CFS2000Data implements IDataProcessor {

    @Autowired
    private AlarmInCommingService alarmInCommingService;

    @Autowired
    private AlarmSocketHandler alarmSocketHandler;

    public void recieve(Object o, String s) {
        UpDownStruct upDownStruct = (UpDownStruct)o;
        Byte cmd = upDownStruct.getCmd();
        System.out.println("cmd:" + cmd);
        if(cmd == 24){
            System.out.println("cmd = 1");
            Up24 o24 = (Up24)o;
            System.out.println(o24.toString());
        }
        if(cmd == 2)
        {
            //上传建筑消防设施部件运行状态
            Up2 o2 = (Up2)o;
            AlarmInComming a = new AlarmInComming();
            a.setIp(IPConver.Ip2Int(s));
            a.setUp_x(TypeFlag.Up2.getName());
            a.setType(UpAnalysis.getSystemTypeChinese(o2.getType()));
            a.setAddr((int)o2.getAddr());
            a.setDev_type(UpAnalysis.getSensorTypeChinese(o2.getDevType()));
            a.setDev_addr(o2.getDevAddr());
            if(o2.getType() == 1) a.setDev_status(UpAnalysis.getSensorStatusChineseSystemType_1(o2.getDevStatus()));
            if(o2.getType() == 100) a.setDev_status(UpAnalysis.getSensorStatusChineseSystemType_100(o2.getDevStatus()));
            if(o2.getType() == 101) a.setDev_status(UpAnalysis.getSensorStatusChineseSystemType_101(o2.getDevStatus()));
            if(o2.getType() == 102) a.setDev_status(UpAnalysis.getSensorStatusChineseSystemType_102(o2.getDevStatus()));
            a.setConfirm_status((byte)0);
            a.setAlarm_time(new Long(System.currentTimeMillis() / 1000).intValue());
            try {
                alarmInCommingService.insertRecord(a);
                alarmSocketHandler.sendAlarmToWeb(new TextMessage("ALARM"));
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    public void onLine(String s, boolean b) {
        //读写数据库用户信息传输装置
        System.out.println("onLine IP: " + s);
        System.out.println("onLine boolean: " + b);
        if(b)
        {
            GlobalDevice.addIp(s);
        }
        else
        {
            GlobalDevice.removeIp(s);
        }
    }

    public void exception(org.apache.mina.core.session.IoSession ioSession, Throwable throwable) {
        System.out.println("协议解析程序异常。");
        throwable.printStackTrace();
    }
}
